/**
 * 
 */
package de.idgard.json.transport;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import de.idgard.json.IDGGson;
import de.idgard.webapp.shared.dto.transport.DataRequest;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public abstract class JsonServiceTransport implements ServiceTransport {

	protected abstract IDGHttpClient getHttpClient();

	protected String getJsonPayload(DataRequest<?> requestPayload) {
		return requestPayload != null ? IDGGson.gson().toJson(requestPayload) : null;
	}

	public <Req> ResponseDescriptor executeRequest(HttpClient httpClient, DataRequest<Req> requestPayload, String url) {
		String jsonPayload = getJsonPayload(requestPayload);
		HttpPost request = null;
		HttpResponse response = null;
		try {
			request = new HttpPost(url);
			if (jsonPayload != null) {
				StringEntity body = new StringEntity(jsonPayload);
				body.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
				request.setEntity(body);
			}
			response = httpClient.execute(request);
			StatusLine status = response.getStatusLine();
			String respBody = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : null;

			return new ResponseDescriptor(status.getStatusCode(), respBody);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseDescriptor(e);
		}
		finally {
			try {
				EntityUtils.consume(response.getEntity());
			} catch (Throwable t) {

			}
		}
	}
}
